package org.liaohailong.library.http;

import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Author: liaohailong
 * Date: 2022/8/12
 * Time: 20:34
 * Description:
 **/
public class HttpHelper {

    static final Gson sGson = new GsonBuilder().create();
    static final Handler sMainHandler = new Handler();
    static final ExecutorService mExecutorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    public static Type[] getClassType(@NonNull Object obj, Class<?> targetClz) {
        Class<?> clz = obj.getClass();
        while (true) {
            Class<?> superClz = clz.getSuperclass();
            if (superClz == targetClz) break;
            if (superClz == Object.class) return new Type[]{};
            clz = superClz;
        }
        Type type = clz.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            return pt.getActualTypeArguments();
        }
        return new Type[]{};
    }

    public static String appendParams(@NonNull String url, @NonNull Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (!params.isEmpty()) {
            int count = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (count <= 0)
                    sb.append("?");
                else
                    sb.append("&");
                count++;

                sb.append(entry.getKey()).append("=").append(entry.getValue());
            }
            sb.append("#");
        }
        return sb.toString();
    }

    public static void post2main(@NonNull Runnable runnable) {
        sMainHandler.post(runnable);
    }

    public static void post2work(@NonNull Runnable runnable) {
        mExecutorService.execute(runnable);
    }


    public static String getFilename(@NonNull String url) {
        if (url.contains("/")) {
            String[] parts = url.split("/");
            String filename = parts[parts.length - 1];
            try {
                return URLDecoder.decode(filename, "UTF-8");
            } catch (Exception ex) {
                return filename;
            }
        }
        return url;
    }

    private static boolean createFileIfNotExist(@NonNull File file) throws IOException {
        if (file.exists()) {
            return true;
        }
        return file.createNewFile();
    }

    public static boolean mkdirsIfNotExist(@NonNull File file) {
        if (file.exists()) {
            if (file.isDirectory()) return true;
            if (!file.delete()) return false;
        }
        return file.mkdirs();
    }

    public static void closeIO(@Nullable Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
